/*******************************************************************************
 * Software Name : Android Simple Downloader
 *
 * Copyright © 2012 Rinvay Tang
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package com.rinvay.network.http.conn.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;

import com.rinvay.network.http.HttpRequest;
import com.rinvay.network.http.conn.HttpConnection;
import com.rinvay.network.http.exception.ErrorMessage;
import com.rinvay.network.http.exception.NetWorkInvalidException;

/**
 * most used default http connection
 * @author rinvay
 * @date 2012-3-10
 */
public class DefaultHttpConnection extends HttpConnection
{
    private static final String TAG = "DefaultHttpConnection";

    protected DefaultHttpConnection(HttpRequest r) {
        this(r, null);
    }

    protected DefaultHttpConnection(HttpRequest request,
            DefaultHttpConnectionListener listener) {
        this.request = request;
        this.listener = listener;
    }
    
    public void handleConnectingFail() {
    }

    public void handleResponse(InputStream in) throws IOException {
        byte[] resp = readStream(in);
        if (listener != null) {
          ((DefaultHttpConnectionListener) listener).onResponse(resp);
      }
    }

    public void handleConnectionFinished() {
    }

    /**
     * read byte from inputstream
     * 
     * @param in
     * @return
     * @throws IOException
     */
    protected static byte[] readStream(InputStream in) throws IOException {
        byte[] buffer = new byte[1024 * 4];
        int len = -1;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while ((len = in.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        byte[] data = baos.toByteArray();
        baos.close();
        return data;
    }

}
